package com.pucheng.bracelet.ui.activity.gpsrun

import android.location.Location
import android.os.Bundle
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
import android.view.animation.AnimationUtils
import android.view.animation.TranslateAnimation
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationClientOption.AMapLocationMode
import com.amap.api.location.AMapLocationListener
import com.amap.api.maps2d.AMap
import com.amap.api.maps2d.CameraUpdateFactory
import com.amap.api.maps2d.LocationSource
import com.amap.api.maps2d.model.MyLocationStyle
import com.blankj.utilcode.util.LogUtils
import com.pucheng.bracelet.R
import com.pucheng.bracelet.app.util.click
import com.pucheng.bracelet.viewmodel.gpsrun.GpsRunningViewModel
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_gps_running.*
import kotlinx.android.synthetic.main.layout_run_mode_map.*
import kotlinx.android.synthetic.main.layout_run_mode_normal.*
import me.hgj.jetpackmvvm.base.activity.BaseVmActivity
import java.util.concurrent.TimeUnit


class GpsRunningActivity : BaseVmActivity<GpsRunningViewModel>(), LocationSource,
    AMapLocationListener {
    private var isDoubleClick: Boolean = false
    private var firstClickTime = 0
    private var secondClickTime = 0
    private var isUp: Boolean = false
    var seconds = 0
    var runingPasueProgress = 0
    var onTuchPauseingDisposable: Disposable? = null
    var onRunDisposable: Disposable? = null

    private var aMap: AMap? = null
    private var onLocationChangedListener: LocationSource.OnLocationChangedListener? = null
    private var aMapLocationClient: AMapLocationClient? = null
    private var aMapLocationClientOption: AMapLocationClientOption? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        aMapview.visibility = View.GONE
        aMapview.onCreate(savedInstanceState)
    }


    override fun onResume() {
        super.onResume()
        this.aMapview.onResume()
    }
    override fun onDestroy() {
        super.onDestroy()
        aMapview.onDestroy()
        val aMapLocationClient = aMapLocationClient
        if (aMapLocationClient != null) {
            aMapLocationClient.onDestroy()
            this.aMapLocationClient = null
        }
    }

    override fun onPause() {
        super.onPause()
        aMapview.onPause();
    }
    override fun createObserver() {

    }

    override fun dismissLoading() {
    }

    override fun initView(savedInstanceState: Bundle?) {
        runTime()

        onClickView()
//        btn_runing_pause.setont
        btn_runing_pause.setOnTouchListener { _, motionEvent ->
            LogUtils.e("action  = " + motionEvent.action)
            if (motionEvent!!.action == MotionEvent.ACTION_DOWN ) {
                btn_runing_pause.visibility = View.GONE
                cpv_runing_pasue_progress.visibility = View.VISIBLE
                onTuchPauseing()
            } else if (motionEvent!!.action == MotionEvent.ACTION_UP ){
                if (runingPasueProgress < 100) {
                    runingPasueProgress = 0
                    btn_runing_pause.visibility = View.VISIBLE
                    cpv_runing_pasue_progress.visibility = View.GONE
                    cpv_runing_pasue_progress.setProgress(0)
                    cpv_runing_pasue_progress.progressRadius = resources.getDimension(R.dimen.dp_90)
                    onTuchPauseingDisposable!!.dispose()
                }
            }
            true
        }

        initMap()
    }

    fun initMap(){
        if (aMap == null) {
            aMap = this.aMapview.map
            m6936M2()
            showLocation()
        }
    }

    private fun showLocation() {
        var myLocationStyle = MyLocationStyle() //初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        myLocationStyle.interval(2000) //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        aMap!!.setMyLocationStyle(myLocationStyle) //设置定位蓝点的Style
//aMap.getUiSettings().setMyLocationButtonEnabled(true);设置默认定位按钮是否显示，非必需设置。
//aMap.getUiSettings().setMyLocationButtonEnabled(true);设置默认定位按钮是否显示，非必需设置。
        aMap!!.isMyLocationEnabled = true // 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。

    }

    private fun m6936M2() {
        aMap!!.mapType = 1
        aMap!!.uiSettings.isZoomControlsEnabled = false
        aMap!!.uiSettings.isZoomControlsEnabled = false
        aMap!!.uiSettings.isMyLocationButtonEnabled = false
        aMap!!.uiSettings.isScaleControlsEnabled = false
        aMap!!.moveCamera(CameraUpdateFactory.zoomTo(16.0f))
        aMap!!.setOnMyLocationChangeListener { p0 -> LogUtils.e("onMyLocationChange${p0}") }
    }

    private fun onClickView() {
        tv_runing_finish.click { finish() }
        tv_runing_continue.click { onContinueRun() }
        ll_runing_map.click { onMapModeClicked() }
        ll_runing_ordinary.click { onNormalModeClicked() }
//        ll_runing_map.click { onMapModeClicked() }
    }

    private fun onTuchPauseing() {
        onTuchPauseingDisposable = Observable.interval(10, TimeUnit.MILLISECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .map { _: Long ->
                runingPasueProgress++
                cpv_runing_pasue_progress.setProgress(runingPasueProgress)
                runingPasueProgress >= 100
            }
            .subscribe { isStop: Boolean ->
                if (isStop) {
                    onPasueRunState()
                    onTuchPauseingDisposable!!.dispose()
                }
            }
    }

    override fun layoutId(): Int = R.layout.activity_gps_running

    override fun showLoading(message: String) {
    }

    private fun runTime() {
        onRunDisposable = Observable.interval(0, 1, TimeUnit.SECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .map { _: Long ->
                val hour: Int = seconds / 3600 % 24
                val minute: Int = seconds % 3600 / 60
                val time =
                    String.format("%02d:%02d:%02d", hour, minute, seconds % 60)
                seconds++
                time
            }
            .subscribe { time: String ->
                tv_runing_time.text = time
                tv_runing_map_minute.text = time
            }
    }

    fun onPasueRunState() {
        rl_runing_pause.visibility = View.GONE
        ll_runing_option.visibility = View.VISIBLE
        runingPasueProgress = 0
        cpv_runing_pasue_progress.setProgress(0)
        cpv_runing_pasue_progress.progressRadius = resources.getDimension(R.dimen.dp_90)
        if (onRunDisposable != null && !onRunDisposable!!.isDisposed) {
            onRunDisposable!!.dispose()
        }
    }

    fun onContinueRun() {
        rl_runing_pause.visibility = View.VISIBLE
        ll_runing_option.visibility = View.GONE
        cpv_runing_pasue_progress.visibility = View.GONE
        btn_runing_pause.visibility = View.VISIBLE
        runingPasueProgress = 0
        cpv_runing_pasue_progress.setProgress(runingPasueProgress)
        runTime()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {

        LogUtils.e("onKeyDown = $keyCode")
        //禁用返回键
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    /**
     * 切换地图模式
     */
    fun onMapModeClicked() {
        val loadAnimation =
            AnimationUtils.loadAnimation(this, R.anim.map_push_in)
        val translateAnimation =
            TranslateAnimation(1, 1.0f, 1, 0.0f, 1, 1.0f, 1, 1.0f)
        translateAnimation.duration = 1500
        this.rl_run_normal.animation = loadAnimation
        this.rl_run_map.animation = translateAnimation
        this.rl_run_normal.visibility = View.GONE
        this.aMapview.visibility = View.VISIBLE
    }
    fun onNormalModeClicked() {
        this.rl_run_normal.animation = AnimationUtils.loadAnimation(
            this,
            R.anim.map_push_out
        )
        this.rl_run_normal.visibility = View.VISIBLE
        this.aMapview.visibility = View.GONE
    }

    /**
     * 停止定位
     */
    override fun deactivate() {
        onLocationChangedListener = null
        val aMapLocationClient = aMapLocationClient
        if (aMapLocationClient != null) {
            aMapLocationClient.stopLocation()
            this.aMapLocationClient!!.onDestroy()
        }
        this.aMapLocationClient = null
    }
    /**
     * 激活定位
     */
    override fun activate(p0: LocationSource.OnLocationChangedListener?) {
        LogUtils.e("激活定位")
        onLocationChangedListener = onLocationChangedListener
        initLocation()
    }

    override fun onLocationChanged(aMapLocation: AMapLocation?) {
        LogUtils.e("aMapLocation = $aMapLocation")
        if (aMapLocation == null) {
            LogUtils.e("aMapLocation is null", arrayOfNulls<Any>(0))
            return
        }
        if (aMapLocation.errorCode == 0) {
            //定位成功，显示小蓝点
            onLocationChangedListener!!.onLocationChanged(aMapLocation)
            m6933J2(aMapLocation)
        } else {
            val sb = StringBuilder()
            sb.append("定位失败,")
            sb.append(aMapLocation.errorCode)
            sb.append(": ")
            sb.append(aMapLocation.errorInfo)
            LogUtils.e(sb.toString(), arrayOfNulls<Any>(0))
        }
    }



    /*定位成功后的操作*/
    private fun m6933J2(aMapLocation: AMapLocation) {
        val accuracy = aMapLocation.accuracy
        val latitude = aMapLocation.latitude
        val longitude = aMapLocation.longitude
        val speed = aMapLocation.speed
//        this.mapRunPresenter.mo16305t(accuracy, latitude, longitude, false)
//        this.mapRunPresenter.mo16290T(speed)
    }

    private fun initLocation() {

        if (aMapLocationClient == null) {
            val aMapLocationClient = AMapLocationClient(applicationContext)
            this.aMapLocationClient = aMapLocationClient
            aMapLocationClient.setLocationListener(this)
        }
        val aMapLocationClientOption = AMapLocationClientOption()
        this.aMapLocationClientOption = aMapLocationClientOption
//        aMapLocationClientOption.locationPurpose = AMapLocationPurpose.Sport
        this.aMapLocationClientOption!!.locationMode = AMapLocationMode.Hight_Accuracy
//        this.aMapLocationClientOption!!.isNeedAddress = false
//        this.aMapLocationClientOption!!.isOnceLocation = false
//        this.aMapLocationClientOption!!.isMockEnable = false
//        this.aMapLocationClientOption!!.interval = 2000
        aMapLocationClient!!.setLocationOption(this.aMapLocationClientOption)
        aMapLocationClient!!.stopLocation()
        aMapLocationClient!!.startLocation()
    }
}